package com.codi.bus.core.service.impl;

import com.codi.base.util.DateUtil;
import com.codi.base.util.DateUtils;
import com.codi.base.util.ExceptionUtil;
import com.codi.base.util.StringUtil;
import com.codi.bus.core.dao.FundDividentsDao;
import com.codi.bus.core.dao.OrganProfileDao;
import com.codi.bus.core.dao.UserDao;
import com.codi.bus.core.domain.FundDividents;
import com.codi.bus.core.domain.OrganProfile;
import com.codi.bus.core.domain.User;
import com.codi.bus.exception.SystemDBException;
import com.codi.trade.dto.HsDividendQryDto;
import com.codi.trade.response.HsFundDividendQryResponse;
import com.codi.trade.service.DividendsQueryService;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 新增分红明细
 */
@Service
@Transactional
public class LocaldataDividentsService {

    private static final Logger logger = LoggerFactory.getLogger(LocaldataDividentsService.class);
    @Autowired
    private DividendsQueryService dividendsQueryService;
    @Autowired
    private FundDividentsDao fundDividentsDao;
    @Autowired
    private UserDao userDao;

    @Autowired
    private OrganProfileDao organProfileDao;

    /**
     * 新增分红明细
     *
     */
    public void addDividents(){
        try {
            logger.info("addDividents");
            //查询获取今天插入的数据
            List<FundDividents> fundDividentsList = fundDividentsDao.selectAllByAffirmDate(DateUtils.formatDate4(DateUtils.addDay(new Date(), -10)));
            List<String> allTaSerialId = new ArrayList<>();
            if(fundDividentsList != null && fundDividentsList.size() != 0){
                for (FundDividents fundDivident : fundDividentsList) {
                    allTaSerialId.add(fundDivident.getTaSerialId());
                }
            }
            //获取所有用户
            List<User> all = Lists.newArrayList();
            List<User> users = userDao.getAllUser();
            if (users != null && users.size() > 0) {
                all.addAll(users);
            }
            //获取机构用户编号
            List<OrganProfile> organProfileList = organProfileDao.queryAllOrganProfiles();
            for (OrganProfile file : organProfileList) {
                User temp = new User();
                temp.setUserId(file.getUserId());
                temp.setExternalClientId(file.getExternalClientId());
                all.add(temp);
            }

            for (User user : all) {
                //用户编号不能为空
                if(user == null || StringUtils.isBlank(user.getExternalClientId())){
                    continue;
                }
                HsDividendQryDto hsDividendQryDto = new HsDividendQryDto();
                hsDividendQryDto.setClient_id(user.getExternalClientId());
                hsDividendQryDto.setConfirmdate_begin(DateUtil.format(DateUtils.addDay(new Date(), -1),"yyyyMMdd"));
                hsDividendQryDto.setReqry_recordsum_flag("1");
                hsDividendQryDto.setRequest_num(50);
                hsDividendQryDto.setQry_beginrownum(1);
                //获取分红明细
                List<HsFundDividendQryResponse> fundDividendQryResponses = dividendsQueryService.query(hsDividendQryDto);
                if(fundDividendQryResponses != null && fundDividendQryResponses.size()!=0){
                    //查询今天是否已经插入过数据
//                    List<FundDividents> dividentslist = fundDividentsDao.selectByClientIdAndAffirmDate(user.getExternalClientId(),DateUtil.format(new Date(),"yyyyMMdd"));
                    //执行插入方法
                    excuteAdd(user,fundDividendQryResponses,allTaSerialId);

                    //返回的记录数有可能大于50  在这里进行判断 大于则多次循环查询
                    if(StringUtil.isEmpty(fundDividendQryResponses.get(0).getTotal_count())){
                        continue;
                    }
                    int totalCount = Integer.valueOf(fundDividendQryResponses.get(0).getTotal_count());
                    if(totalCount > 50){
                        if(totalCount % 50 != 0){
                            int count = totalCount/50 + 1;
                            for (int i = 1; i < count; i++) {
                                //直接从第2次循环开始
                                HsDividendQryDto extra = new HsDividendQryDto();
                                extra.setClient_id(user.getExternalClientId());
                                extra.setConfirmdate_begin(DateUtil.format(DateUtils.addDay(new Date(), -1), "yyyyMMdd"));
                                extra.setReqry_recordsum_flag("0");
                                extra.setRequest_num(50);
                                extra.setQry_beginrownum((50*i)+1);
                                List<HsFundDividendQryResponse> extraResponses = dividendsQueryService.query(extra);
                                if(extraResponses == null || extraResponses.size() == 0){
                                    logger.error("addDividents第"+(i+1)+"次查询失败，用户："+user.getExternalClientId());
                                    return;
                                }
                                excuteAdd(user,extraResponses,allTaSerialId);
                            }
                        }else{
                            int count = totalCount/50;
                            for (int i = 1; i < count; i++) {
                                //直接从第2次循环开始
                                HsDividendQryDto extra = new HsDividendQryDto();
                                extra.setClient_id(user.getExternalClientId());
                                extra.setConfirmdate_begin(DateUtil.format(DateUtils.addDay(new Date(), -1), "yyyyMMdd"));
                                extra.setReqry_recordsum_flag("0");
                                extra.setRequest_num(50);
                                extra.setQry_beginrownum((50*i)+1);
                                List<HsFundDividendQryResponse> extraResponses = dividendsQueryService.query(extra);
                                if(extraResponses == null || extraResponses.size() == 0){
                                    logger.error("addDividents第"+(i+1)+"次查询失败，用户："+user.getExternalClientId());
                                    return;
                                }
                                excuteAdd(user,extraResponses,allTaSerialId);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            ExceptionUtil.logError(logger, "新增分红明细addDividents - Exception:", e);
            throw new SystemDBException("新增分红明细addDividents Failure!", e);
        }
    }

    /**
     * 插入方法
     * @param user
     * @param fundDividendQryResponses
     */
    public void excuteAdd(User user,List<HsFundDividendQryResponse> fundDividendQryResponses,List<String> allTaSerialId){
        //填充到分红明细表实体类并插入数据
        for (HsFundDividendQryResponse fundDividendQryRespons : fundDividendQryResponses) {
            // 记录数
            String rowCount = fundDividendQryRespons.getRowcount();
            if (StringUtil.isEmpty(rowCount)) {
                return;
            }
            String successType = fundDividendQryRespons.getSuccess_type();
            if(successType.equals("1")){
                logger.error("新增分红明细addDividents:1-系统级错误,当前用户={}",user.getUserId());
                return;
            }else if (successType.equals("2")){
                logger.error("新增分红明细addDividents:2-应用级错误,当前用户={}",user.getUserId());
                return;
            }else if (successType.equals("3")){
                logger.error("新增分红明细addDividents:3-业务级错误,当前用户={}",user.getUserId());
                return;
            }
//            if(dividentslist != null && dividentslist.size() != 0){
////                //验证是否插入过相同的数据  判断条件：交易账号、TA确认编号、基金代码
////                boolean flag = false;
////                for (FundDividents fundDividents : dividentslist) {
////                    if(fundDividendQryRespons.getTrade_acco().equals(fundDividents.getTradeAcco()) && fundDividendQryRespons.getFund_code().equals(fundDividents.getFundCode()) && fundDividendQryRespons.getTa_serial_id().equals(fundDividents.getTaSerialId())){
////                        flag = true;
////                        break;
////                    }
////                }
////                if(flag){
////                    continue;
////                }
////            }

            //只插入现金分红数据  0：红利再投资  1：现金分红
            if(fundDividendQryRespons.getAuto_buy().equals("1")) {

                FundDividents fundDividents = new FundDividents();
                fundDividents.setUserId(user.getUserId().intValue());
                fundDividents.setClientId(user.getExternalClientId());
                fundDividents.setTradeAcco(fundDividendQryRespons.getTrade_acco());
                fundDividents.setTaAcco(fundDividendQryRespons.getTa_acco());
                fundDividents.setFundCode(fundDividendQryRespons.getFund_code());
                fundDividents.setTaSerialId(fundDividendQryRespons.getTa_serial_id());
                fundDividents.setAffirmDate(fundDividendQryRespons.getAffirm_date());
                fundDividents.setEquityRegDate(fundDividendQryRespons.getEquity_reg_date());
                fundDividents.setDividendDate(fundDividendQryRespons.getDividend_date());
                fundDividents.setRegShare(new BigDecimal(fundDividendQryRespons.getReg_share()));
                fundDividents.setUnitBala(new BigDecimal(fundDividendQryRespons.getUnit_bala()));
                fundDividents.setUnitShare(new BigDecimal(fundDividendQryRespons.getUnit_share()));
                fundDividents.setDividendShare(new BigDecimal(fundDividendQryRespons.getDividend_share()));
                fundDividents.setDividendBala(new BigDecimal(fundDividendQryRespons.getDividend_bala()));
                fundDividents.setDividendTotalbala(new BigDecimal(fundDividendQryRespons.getDividend_totalbala()));
                fundDividents.setFrozenShares(new BigDecimal(fundDividendQryRespons.getFrozen_shares()));
                fundDividents.setFrozenBala(new BigDecimal(fundDividendQryRespons.getFrozen_bala()));
                fundDividents.setNetValue(new BigDecimal(fundDividendQryRespons.getNet_value()));
                fundDividents.setAutoBuy(fundDividendQryRespons.getAuto_buy());

                if(!allTaSerialId.contains(fundDividents.getTaSerialId())){
                    fundDividentsDao.insert(fundDividents);
                }
            }
        }
    }

}
